package ch.bfh.medinfo.javafx.dice.a_3;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.input.InputEvent;
import ch.bfh.medinfo.javafx.dice.definition.Dice;
import ch.bfh.medinfo.javafx.dice.implementation.FairDice;

public class DiceController {
	private Dice dice;
	private boolean isDicePlaying;
	private Runnable dicePlaying;

	public DiceController() {
		this.dice = new FairDice(1, 6);
		dicePlaying = new DicePlaying();
		Thread t = new Thread(new DicePlaying());
		t.start();

	}

	@FXML
	private ResourceBundle resources;

	@FXML
	private URL location;

	@FXML
	private Label labelActualValueId;

	@FXML
	void playStart(InputEvent event) {
		//Or if inputEvent is known: (ActionEvent event)
		synchronized (dicePlaying) {
			isDicePlaying = true;
			dicePlaying.notifyAll();
		}
	}

	@FXML
	void playStop(InputEvent event) {
		//Or if inputEvent is known: (MouseEvent event)
		synchronized (dicePlaying) {
			isDicePlaying = false;
			dicePlaying.notifyAll();
		}

	}

	@FXML
	void initialize() {
		assert labelActualValueId != null : "fx:id=\"labelActualValueId\" was not injected: check your FXML file 'SimpleDiceView.fxml'.";

	}

	class DicePlaying implements Runnable {
		final Runnable diceUpdater = new Runnable() {

			@Override
			public void run() {
				labelActualValueId.setText("" + dice.getActualValue());
			}
		};

		@Override
		public void run() {
			boolean playing = false;
			while (!Thread.currentThread().isInterrupted()) {
				synchronized (dicePlaying) {
					playing = isDicePlaying;
				}
				if (!playing) {
					synchronized (dicePlaying) {
						try {
							dicePlaying.wait();
						} catch (InterruptedException e) {
							Thread.currentThread().interrupt();
						}
					}
				}
				if (playing) {
					synchronized (dicePlaying) {
						dice.play();
						// It is important to update the text of the label on
						// the JavaFX-Application-Thread.
						Platform.runLater(diceUpdater);

					}
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
					}
				}

			}

		}

	}

}
